package com.kooison.idevice4u.email;

import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GAEMail {
	private final Logger logger = Logger.getLogger(this.getClass().getName());
	
	private String msgBody;
	private String fromAddress;
	private String[] toAddress;
	private String[] ccAddress;
	private String[] bccAddress;
	private String subject;
	
	public void setMsgBody(String msgBody) {
		this.msgBody = msgBody;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public void setToAddress(String[] toAddress) {
		this.toAddress = toAddress;
	}

	public void setCcAddress(String[] ccAddress) {
		this.ccAddress = ccAddress;
	}

	public void setBccAddress(String[] bccAddress) {
		this.bccAddress = bccAddress;
	}
	
	public void setSubject(String subject) {
		this.subject = subject;
	}

	private static InternetAddress[] getInternetAddress(String[] addressArray) throws AddressException {
		InternetAddress[] tmpAddress = new InternetAddress[addressArray.length];
		for (int i = 0; i < addressArray.length; i++) {
			tmpAddress[i] = new InternetAddress(addressArray[i]);
		}
		return tmpAddress;
	}
	
	public void send() {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(fromAddress));
			if (toAddress != null && toAddress.length > 0)
				msg.addRecipients(Message.RecipientType.TO, getInternetAddress(toAddress));
			if (ccAddress != null && ccAddress.length > 0)
				msg.addRecipients(Message.RecipientType.CC, getInternetAddress(ccAddress));
			if (bccAddress != null && bccAddress.length > 0)
				msg.addRecipients(Message.RecipientType.BCC, getInternetAddress(bccAddress));
			msg.setSubject(subject);
			msg.setContent(msgBody, "text/html; charset=utf-8");
			Transport.send(msg);
			logger.info("Mail was sent");
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
